import router, { resetRouter, setAppData } from "/@/router";
import { login, getCaptchaImgUrl, saveLoginLog } from "/@/api/aiot/user";
import { buildShortUUID } from "/@/utils/uuid";
import authCache from "/@/utils/cache/authCache";
import { useI18n } from "/@/locales/useI18n";
import { message } from "ant-design-vue";
import md5 from "/@/utils/md5";
import { defineStore } from "pinia";
import { useApplicationStore } from "/@/stores/aiot/application";
import { useUserStore } from "/@/stores/aiot/user";
import { ApplicationItem, AppTypeEnum } from "/@/api/aiot/application/models";
import { GrantTypeEnum } from "/@/api/aiot/user/models";
import type { LoginParams, TenantInfo } from "/@/api/aiot/user/models";
import { appRouteData } from "/@/router";
import { AiotSubApp } from "/@/base/data";
import { AIOT_ROUTE_NAME } from "/@/router";

export interface AccountState {
  account: string;
  name: string;
  captchaKey: string;
  userId: number | null | string;
}

// const FIRST_ROUTE = "/aiot/project/projectCenter";

export const useAccountStore = defineStore("account", {
  state: (): AccountState => {
    return {
      account: "",
      name: "",
      captchaKey: "",
      userId: null,
    };
  },
  actions: {
    async login(params: LoginParams) {
      // const rememberMe = params.rememberMe;
      delete params.rememberMe;
      params.appType = AppTypeEnum.PC;
      params.grantType = GrantTypeEnum.PASSWORD;
      params.appCode = AiotSubApp.AIOT;
      params.key = this.captchaKey;
      if (!params.isRemPass) {
        params.password = md5(params.password);
      }
      const result = await login(params);
      if (!result) return null;
      authCache.setRemUserInfo({
        account: params.account,
        //888888
        password: params.password,
      });
      // if (rememberMe) {
      //   authCache.setRemUserInfo({
      //     account: params.account,
      //     //888888
      //     password: params.password,
      //   });
      // } else {
      //   authCache.setRemUserInfo(null);
      // }
      const { authInfo } = result;
      authCache.setUserInfo({
        userId: authInfo.userId,
        account: authInfo.account,
        name: authInfo.name,
      });
      authCache.setToken(authInfo.token);
      this.account = authInfo.account;
      this.name = authInfo.name;
      this.userId = authInfo.userId;
      return result;
    },
    getCaptchaImgUrl() {
      this.captchaKey = buildShortUUID();
      return getCaptchaImgUrl(this.captchaKey);
    },
    /**
     * 登录后选择租户
     * @param tenantInfo 所选的租户信息
     */
    async chooseTenant(tenantInfo: TenantInfo, isChangeTenant?: boolean) {
      //缓存租户id 跟token一起放header
      const tenantId = tenantInfo.tenantId;
      authCache.setTenant(window.btoa(tenantId as string));
      const store = useApplicationStore();
      if (isChangeTenant) {
        const appData = store.applicationData;
        const code = appData.length > 0 ? appData[0].applicationCode : AIOT_ROUTE_NAME;
        router.replace("/" + (code as string)).then(() => {
          location.reload();
        });
        return;
      }
      const userStore = useUserStore();
      //同步设置最大角色权限 方便菜单权限判断
      userStore.detail.userTenantInfoVo.tenantMaxRole = tenantInfo.tenantMaxRole;
      //重置路由数据
      resetRouter();
      if (!isChangeTenant) {
        //保存登录日志
        saveLoginLog();
      }
      //获取当前租户的应用数据
      const appData = await store.initApplicationData();
      if (appData && appData.length > 0) {
        setAppData(appData);
        //判断登录后第一次展示的页面路由是否存在
        try {
          await router.push("/" + (appData[0].applicationCode as string));
          return true;
        } catch (ex) {
          console.log("=================>chooseTenant error", ex);
          return false;
        }
      } else {
        const { t } = useI18n();
        message.error(appData ? t("common.noAppData") : t("common.errAppData"));
        return false;
      }
    },
    handleTenantList(tenantInfos: TenantInfo[]) {
      const { t } = useI18n();
      tenantInfos.forEach((tenantInfo) => {
        if (tenantInfo.isLock) {
          tenantInfo.errorMsg = t("aiot.login.accountDisabled");
        } else if (!tenantInfo.beginTimeValid) {
          tenantInfo.errorMsg = t("aiot.login.unvalid", { date: tenantInfo.expirationDateFrom });
        } else if (!tenantInfo.endTimeValid) {
          tenantInfo.errorMsg = t("aiot.login.expire", { date: tenantInfo.expirationDateTo });
        } else {
          tenantInfo.errorMsg = "";
        }
      });
    },
  },
});
